/**
 * API日志工具
 *
 * 功能特性：
 * - 详细的API调用日志记录（仅开发环境）
 * - 请求/响应数据记录
 * - 错误信息详细记录
 * - 性能监控
 * - 请求ID追踪
 *
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

// 日志级别枚举
export enum LogLevel {
  NONE = 0,
  ERROR = 1,
  INFO = 2,
  DEBUG = 3
}

// 日志配置接口
export interface LogConfig {
  level: LogLevel;
  enablePerformance: boolean;
  enableRequestId: boolean;
  maxDataLength: number;
}

// 请求日志信息接口
export interface RequestLog {
  id: string;
  method: string;
  url: string;
  headers?: Record<string, string>;
  data?: any;
  params?: any;
  timestamp: string;
}

// 响应日志信息接口
export interface ResponseLog {
  id: string;
  status: number;
  statusText: string;
  data?: any;
  headers?: Record<string, string>;
  duration: number;
  timestamp: string;
}

// 错误日志信息接口
export interface ErrorLog {
  id: string;
  message: string;
  status?: number;
  statusText?: string;
  data?: any;
  config?: any;
  timestamp: string;
}

// 默认配置
const defaultConfig: LogConfig = {
  level: LogLevel.DEBUG,
  enablePerformance: true,
  enableRequestId: true,
  maxDataLength: 1000
};

/**
 * API日志工具类
 */
class ApiLogger {
  private config: LogConfig;
  private activeRequests: Map<string, { startTime: number; request: RequestLog }> = new Map();

  constructor(config: Partial<LogConfig> = {}) {
    this.config = { ...defaultConfig, ...config };
  }

  /**
   * 生成请求ID
   */
  private generateRequestId(): string {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 格式化数据用于日志显示
   */
  private formatData(data: any): string {
    if (!data) return '';

    try {
      const dataStr = JSON.stringify(data, null, 2);
      if (dataStr.length > this.config.maxDataLength) {
        return dataStr.substring(0, this.config.maxDataLength) + '... [truncated]';
      }
      return dataStr;
    } catch (error) {
      return `[无法序列化的数据: ${typeof data}]`;
    }
  }

  /**
   * 格式化时间戳
   */
  private formatTimestamp(timestamp: string): string {
    return new Date(timestamp).toLocaleTimeString();
  }

  /**
   * 获取彩色日志前缀
   */
  private getColorPrefix(type: 'request' | 'response' | 'error'): string {
    const colors = {
      request: '🚀',
      response: '✅',
      error: '❌'
    };
    return colors[type];
  }

  /**
   * 记录请求开始
   */
  public logRequest(method: string, url: string, config?: any): string {
    if (this.config.level < LogLevel.DEBUG) return '';

    const requestId = this.config.enableRequestId ? this.generateRequestId() : '';
    const timestamp = new Date().toISOString();

    const requestLog: RequestLog = {
      id: requestId,
      method,
      url,
      headers: config?.headers,
      data: config?.data,
      params: config?.params,
      timestamp
    };

    this.activeRequests.set(requestId, {
      startTime: Date.now(),
      request: requestLog
    });

    console.group(`%c${this.getColorPrefix('request')} API请求: ${method.toUpperCase()} ${url}`,
      'color: #2196F3; font-weight: bold');

    console.log(`%c请求ID: ${requestId}`, 'color: #666; font-size: 12px');
    console.log(`%c时间: ${this.formatTimestamp(timestamp)}`, 'color: #666; font-size: 12px');

    if (config?.headers && this.config.level >= LogLevel.DEBUG) {
      console.log('%c请求头:', 'color: #4CAF50; font-weight: bold', config.headers);
    }

    if (config?.data && this.config.level >= LogLevel.DEBUG) {
      console.log('%c请求数据:', 'color: #FF9800; font-weight: bold', this.formatData(config.data));
    }

    if (config?.params && this.config.level >= LogLevel.DEBUG) {
      console.log('%c请求参数:', 'color: #9C27B0; font-weight: bold', config.params);
    }

    console.groupEnd();

    return requestId;
  }

  /**
   * 记录响应成功
   */
  public logResponse(requestId: string, response: any, config?: any): void {
    if (this.config.level < LogLevel.INFO) return;

    const activeRequest = this.activeRequests.get(requestId);
    if (!activeRequest) return;

    const { startTime, request } = activeRequest;
    const duration = this.config.enablePerformance ? Date.now() - startTime : 0;
    const timestamp = new Date().toISOString();

    const responseLog: ResponseLog = {
      id: requestId,
      status: response?.status || 200,
      statusText: response?.statusText || 'OK',
      data: response?.data,
      headers: response?.headers,
      duration,
      timestamp
    };

    console.group(`%c${this.getColorPrefix('response')} API响应: ${request.method.toUpperCase()} ${request.url}`,
      'color: #4CAF50; font-weight: bold');

    console.log(`%c请求ID: ${requestId}`, 'color: #666; font-size: 12px');
    console.log(`%c时间: ${this.formatTimestamp(timestamp)}`, 'color: #666; font-size: 12px');
    console.log(`%c状态: ${responseLog.status} ${responseLog.statusText}`,
      responseLog.status < 400 ? 'color: #4CAF50; font-weight: bold' : 'color: #F44336; font-weight: bold');

    if (this.config.enablePerformance && duration > 0) {
      const color = duration > 1000 ? '#F44336' : duration > 500 ? '#FF9800' : '#4CAF50';
      console.log(`%c响应时间: ${duration}ms`, `color: ${color}; font-weight: bold`);
    }

    if (response?.data && this.config.level >= LogLevel.DEBUG) {
      console.log('%c响应数据:', 'color: #2196F3; font-weight: bold', this.formatData(response.data));
    }

    console.groupEnd();

    // 清理活动请求
    this.activeRequests.delete(requestId);
  }

  /**
   * 记录响应错误
   */
  public logError(requestId: string, error: any, config?: any): void {
    if (this.config.level < LogLevel.ERROR) return;

    const activeRequest = this.activeRequests.get(requestId);
    const request = activeRequest?.request;
    const duration = activeRequest ? Date.now() - activeRequest.startTime : 0;
    const timestamp = new Date().toISOString();

    const errorLog: ErrorLog = {
      id: requestId,
      message: error?.message || 'Unknown error',
      status: error?.response?.status,
      statusText: error?.response?.statusText,
      data: error?.response?.data,
      config: error?.config,
      timestamp
    };

    console.group(`%c${this.getColorPrefix('error')} API错误: ${request?.method?.toUpperCase() || 'UNKNOWN'} ${request?.url || 'UNKNOWN'}`,
      'color: #F44336; font-weight: bold');

    if (requestId) {
      console.log(`%c请求ID: ${requestId}`, 'color: #666; font-size: 12px');
    }
    console.log(`%c时间: ${this.formatTimestamp(timestamp)}`, 'color: #666; font-size: 12px');
    console.log(`%c错误信息: ${errorLog.message}`, 'color: #F44336; font-weight: bold');

    if (errorLog.status) {
      console.log(`%c状态码: ${errorLog.status} ${errorLog.statusText || ''}`, 'color: #F44336; font-weight: bold');
    }

    if (this.config.enablePerformance && duration > 0) {
      console.log(`%c耗时: ${duration}ms`, 'color: #FF9800; font-weight: bold');
    }

    if (error.response?.data && this.config.level >= LogLevel.DEBUG) {
      console.log('%c错误数据:', 'color: #F44336; font-weight: bold', this.formatData(error.response.data));
    }

    if (error.config && this.config.level >= LogLevel.DEBUG) {
      console.log('%c请求配置:', 'color: #9C27B0; font-weight: bold', this.formatData(error.config));
    }

    console.groupEnd();

    // 清理活动请求
    this.activeRequests.delete(requestId);
  }

  /**
   * 创建增强的axios拦截器
   */
  public createAxiosInterceptors(axiosInstance: any) {
    // 请求拦截器
    axiosInstance.interceptors.request.use((config: any) => {
      const requestId = this.logRequest(config.method?.toUpperCase() || 'GET', config.url, config);
      config.metadata = { requestId };
      return config;
    });

    // 响应拦截器
    axiosInstance.interceptors.response.use(
      (response: any) => {
        const requestId = response.config.metadata?.requestId;
        if (requestId) {
          this.logResponse(requestId, response, response.config);
        }
        return response;
      },
      (error: any) => {
        const requestId = error.config?.metadata?.requestId;
        if (requestId) {
          this.logError(requestId, error, error.config);
        }
        return Promise.reject(error);
      }
    );
  }

  /**
   * 获取活动请求数量
   */
  public getActiveRequestCount(): number {
    return this.activeRequests.size;
  }

  /**
   * 清理所有活动请求
   */
  public clearAllRequests(): void {
    this.activeRequests.clear();
  }

  /**
   * 更新配置
   */
  public updateConfig(newConfig: Partial<LogConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }
}

// 创建全局实例
const apiLogger = new ApiLogger({
  level: process.env.NODE_ENV === 'development' ? LogLevel.DEBUG : LogLevel.ERROR,
  enablePerformance: true,
  enableRequestId: true,
  maxDataLength: 1000
});

// 导出工具函数
export const createApiLogger = (config?: Partial<LogConfig>) => new ApiLogger(config);

// 导出便捷函数
export const logApiCall = (
  method: string,
  url: string,
  config?: any
): string => {
  return apiLogger.logRequest(method, url, config);
};

export const logApiSuccess = (
  requestId: string,
  response: any,
  config?: any
): void => {
  apiLogger.logResponse(requestId, response, config);
};

export const logApiFailure = (
  requestId: string,
  error: any,
  config?: any
): void => {
  apiLogger.logError(requestId, error, config);
};

// 导出默认实例
export default apiLogger;